﻿
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Text.Json;

using MySql.Data.MySqlClient;

using Org.BouncyCastle.Asn1.X509.Qualified;

using zijian666.Data;
using zijian666.Data.SqlBuilders;

namespace demo;

class Program
{
    static async Task Main()
    {
        Diagnostic.IsDebug = true;

        Diagnostic.Subscribe(new DiagnosticObserver());

        DbProviderFactories.RegisterFactory("MySql.Data.MySqlClient", MySqlClientFactory.Instance);
        // pg
        DbProviderFactories.RegisterFactory("Npgsql", Npgsql.NpgsqlFactory.Instance);

        DbInterceptors.AddDiagnostic();


        var table = new DataTable();
        table.TableName = "json_test";
        table.Columns.Add("id", typeof(Guid));
        table.Columns.Add("data", typeof(string));

        var row = table.NewRow();
        row["id"] = Guid.NewGuid();
        row["data"] = JsonSerializer.Serialize(new json_data { name = "test", age = 18 });
        table.Rows.Add(row);

        var reader = table.CreateDataReader();
        //reader.Read();
        //var aa = EntityBuilder.Read<json_data>(reader, 1);

        var result = await reader.ReadListAsync<json_test>();

        var json = JsonSerializer.Serialize(result);
        Console.WriteLine(json);

    }
}

[Table("json_test")]
class json_test
{
    [Column("id")]
    [Key]
    public Guid id { get; set; }

    [Column("data", TypeName = "jsonb")]
    public json_data data { get; set; }

    public json_test[] Tests { get; set; }

}

class json_data
#if NET8_0_OR_GREATER
    : IDataSerializer<json_data, string>
#endif
{
    public string name { get; set; }
    public int age { get; set; }

    public string ToDbValue()
    {
        return JsonSerializer.Serialize(this);
    }

    public static json_data FromDbValue(string dbValue)
    {
        return JsonSerializer.Deserialize<json_data>(dbValue)!;
    }
}